package cn.blnp.net.flowable.api.task;

import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.TaskService;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <h3></h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/4/29 14:37
 */
@Slf4j
@Component
public class MyTaskService {

    @Resource
    private TaskService taskService;

    public MyTaskService(TaskService taskService) {
        this.taskService = taskService;
    }
    public void complete(String taskId, String userId) {
        log.warn("{}尝试办理ID为{}的任务", userId, taskId);
        Task curTask = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (curTask == null || curTask.getAssignee() != null) {
            log.warn("任务不存在或已被其他候选人办理完成");
            return;
        }
        //查找用户与任务的关系
        List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(taskId);
        IdentityLink userIdentityLink = null;
        for (IdentityLink identityLink : identityLinks) {
            if (identityLink.getUserId().equals(userId)) {
                userIdentityLink = identityLink;
                break;
            }
        }
        if (userIdentityLink == null) {
            log.warn("{} 没有权限查看ID为 {} 的任务", userId, taskId);
        } else {
            log.warn("{} 是任务的 {}", userId, userIdentityLink.getType());
            if (userIdentityLink.getType().equals("candidate")) {
                //认领任务
                taskService.claim(taskId, userId);
                //设置审批意见
                Map<String, Object> variables = new HashMap<>();
                variables.put("task_审批_outcome", "agree");
                taskService.complete(taskId, variables);
                log.warn("{} 完成了ID为 {} 的任务的办理", userId, taskId);
            } else {
                log.warn("{} 没有权限办理ID为 {} 的任务", userId, taskId);
            }
        }
    }
}
